package com.cloudjan.springcloud.controller;

import com.cloudjan.springcloud.entities.CommonResult;
import com.cloudjan.springcloud.entities.Payment;
import com.cloudjan.springcloud.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController
@Slf4j
public class PaymentController {
    @Autowired
    private PaymentService paymentService;

    @Value("${server.port}")
    private String serverport;

    @Resource
    private DiscoveryClient discoveryClient;

    @PostMapping(value = "/payment/create")
    public CommonResult create(@RequestBody Payment payment) {
        int result = paymentService.create(payment);
        log.info("插入结果=={}", payment);
        if (result > 0) {
            return new CommonResult(200, "插入成功！,serverport=" + serverport, result);
        } else {
            return new CommonResult(444, "插入失败！");
        }
    }

    @GetMapping(value = "/payment/get/{id}")
    public CommonResult<Payment> get(@PathVariable("id") Long id) {
        Payment result = paymentService.getPaymentById(id);
        log.info("查询的结果=={}", result);
        if (result != null) {
            return new CommonResult(200, "查询成功,serverport=" + serverport, result);
        } else {
            return new CommonResult(444, "记录不存在，id={}" + id);
        }
    }

    /**
     * 测试服务发现，获取所有微服务信息
     * @return
     */
    @GetMapping("/payment/discovery")
    public Object discovery() {
        List<String> services = discoveryClient.getServices();
        for (String service : services) {
            log.info("*******elment:" + service + "*********");
        }
        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        for (ServiceInstance instance : instances) {
            log.info(instance.getHost()+"\t"+instance.getPort()+"\t"+instance.getUri());
        }
        return discoveryClient;
    }

    /**
     * 用于测试自定义的轮询负载均衡算法
     * @return
     */
    @GetMapping("/payment/lb")
    public String getServerport(){
        return serverport;
    }

    /**
     * 测试feign超时时间
     * @return
     */
    @GetMapping("/payment/feign/timeout")
    public String paymentFeignTimeout(){
        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return serverport;
    }
}
